package com.tz;

import com.tz.util.EntityInterceptor;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by robin on 2016/8/5 0005.
 */
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
@EnableTransactionManagement
@PropertySource("classpath:app.properties")
public class AppConfig {
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource(){
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(env.getProperty("driver.class.name"));
        basicDataSource.setUrl(env.getProperty("datasource.url"));
        basicDataSource.setUsername(env.getProperty("datasource.username"));
        basicDataSource.setPassword(env.getProperty("datasource.password"));
        return basicDataSource;
    }

    @Bean
    public LocalSessionFactoryBean lsfb() {
        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
        lsfb.setDataSource(dataSource());
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        props.setProperty("hibernate.hbm2ddl.auto", "update");
        props.setProperty("hibernate.show_sql", "true");
        lsfb.setHibernateProperties(props);
        lsfb.setPackagesToScan("com.tz.entity");
        Interceptor interceptor = new EntityInterceptor();
        lsfb.setEntityInterceptor(interceptor);
        return lsfb;
    }


    @Bean
    public HibernateTransactionManager tm() {
        HibernateTransactionManager tm = new HibernateTransactionManager();
        tm.setSessionFactory(lsfb().getObject());
        return tm;
    }
}
